package com.intelligent.system.auth.filter;

import com.intelligent.system.auth.entity.UserToken;
import com.intelligent.system.auth.uitls.OAuth2UserInfoUtils;
import com.intelligent.system.auth.uitls.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * Token认证过滤器
 * 用于处理token的验证和用户认证
 */

@Slf4j
@Component
public class OAuth2TokenAuthenticationFilter extends OncePerRequestFilter {

    @Resource
    private TokenUtils tokenUtils;

    @Resource
    private OAuth2UserInfoUtils userInfoUtils;

    private final PathMatcher pathMatcher = new AntPathMatcher();

    // 不需要token验证的路径
    private static final List<String> EXCLUDE_PATHS = Arrays.asList(
        "/api/oauth/**",      // OAuth2相关接口
        "/error",            // 错误页面
        "/swagger-ui.html",  // Swagger UI
        "/swagger-ui/**",    // Swagger UI资源
        "/swagger-resources/**", // Swagger资源
        "/v2/api-docs",      // Swagger API文档
        "/v3/api-docs",      // OpenAPI文档
        "/webjars/**"        // Swagger UI依赖
    );

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        String path = request.getRequestURI();
        for (String pattern : EXCLUDE_PATHS) {
            if (pathMatcher.match(pattern, path)) {
                log.debug("请求路径 {} 在排除列表中，跳过认证", path);
                return true;
            }
        }
        log.debug("请求路径 {} 不在排除列表中，需要认证", path);
        return false;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 直接放行所有请求
        filterChain.doFilter(request, response);
    }
}
